<?php
 
 
namespace D3hdv\HdvBundle\Controller;


use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;

use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;

class HdvAdminController extends Controller
{


  public function RedirectionAction()
  {
	/*return $this->container->get('templating')->renderResponse('D3hdvHdvBundle:Admin:index.html.twig', array(
	
	));*/
	return $this->redirect($this->generateUrl('_security_login_hdv_admin'));
  }

  public function IndexAction()
  {
	return $this->container->get('templating')->renderResponse('D3hdvHdvBundle:Admin:index.html.twig', array(
	
	));
	
  }

   public function VoirComptesHdvAction($page)
   {
	$em = $this->getDoctrine()->getEntityManager();
	$total = $this->getDoctrine()->getRepository('D3hdvHdvBundle:HdvCompte')->createQueryBuilder('p')->getQuery()->getResult();
         
        /* total of résultat */
        $total_articles    = count($total);
        $articles_per_page = $this->container->getParameter('max_on_listepage');
        $last_page         = ceil($total_articles / $articles_per_page);
        $previous_page     = $page > 1 ? $page - 1 : 1;
        $next_page         = $page < $last_page ? $page + 1 : $last_page;
        /* résultat  à afficher*/
        $HdvComptes          = $this->getDoctrine()->getRepository('D3hdvHdvBundle:HdvCompte')->createQueryBuilder('p')->setFirstResult(($page * $articles_per_page) - $articles_per_page)->setMaxResults($this->container->getParameter('max_on_listepage'))->getQuery()->getResult();
	if (!$HdvComptes) {
		    throw $this->createNotFoundException('Unable to find Compte Hdv entity.');
		}
        return $this->render('D3hdvHdvBundle:Admin:voir_comptes_hdv.html.twig', array(
            'HdvComptes' => $HdvComptes,
            'last_page' => $last_page,
            'previous_page' => $previous_page,
            'current_page' => $page,
            'next_page' => $next_page,
            'total_comptes' => $total_articles,
        ));
   }

   public function SupprimerCompteHdvAction($idcomptehdv) // Ajouter l'annulation de toutes les ventes de ce compte
   {
	$em = $this->container->get('doctrine')->getEntityManager();
	$CompteHdv = $this->getDoctrine()->getEntityManager()->getRepository('D3hdvHdvBundle:HdvCompte')->findById($idcomptehdv);


    if(!is_null($CompteHdv[0]->getDiablo3Compte()))
    {
	$HdvCompteDiablo3Coffre =$CompteHdv[0]->getDiablo3Compte()->getCoffre();
	$HdvCompteObjetsEnVente=$CompteHdv[0]->getObjetsEnVente();
	$HdvVenteObjetVendu="";
	
	foreach($HdvCompteObjetsEnVente as $j => $HdvVente)  
	{
			$HdvVenteObjetVendu=$HdvVente->GetD3Objet();
			$HdvVenteObjetVenduDateFin=$HdvVente->GetDateFin();
           // echo "avant ".$HdvVenteObjetVenduDateFin->format('Y-m-d H:i:s')."<br>";
			if(is_null($HdvVenteObjetVenduDateFin))
			{
               // echo "apres ".$HdvVenteObjetVenduDateFin->format('Y-m-d H:i:s')."<br>";
				$qb = $em->createQueryBuilder();
				$qb->select('v')
				->from('D3hdvDiablo3Bundle:D3CoffreD3Objet', 'v')
				->where("v.D3Coffre = ?1 and v.D3Objet= ?2")
				->setParameter(1,$HdvCompteDiablo3Coffre)
				->setParameter(2,$HdvVenteObjetVendu);

				$query = $qb->getQuery();               
				$D3ObjetD3Coffre = $query->getResult();	
				if(!empty($D3ObjetD3Coffre)) // Objet dans la table HdvVente donc déja vendu
				{
					foreach($D3ObjetD3Coffre as $o => $D3Objet)  
					{
						$D3Objet->SetEnVente(false);
						$em->persist($D3Objet);
						$em->flush();
					}
				}
				$CompteHdv[0]->removeObjetsEnVente($HdvVente);
                
				$em->persist($CompteHdv[0]);
				$em->flush();
             
				$em->remove($HdvVente);
				$em->flush();
			}

					
	}
/*Modification récente*/
	$qb = $em->createQueryBuilder();
	$qb->select('d')
	->from('D3hdvHdvBundle:HdvVente', 'd') // revoir requete probleme on selectionne tout les ventes :s
	->where("d.CompteAcheteur = ".$CompteHdv[0]->GetId())
	;

	$query = $qb->getQuery();               
	$HdvAchats = $query->getResult();
	foreach($HdvAchats as $j => $HdvAchat)  
	{
		$HdvAchat->removeCompteAcheteur();
		$em->persist($HdvAchat);
		$em->flush();
	}

	$CompteHdv[0]->removeDiablo3Compte();

	$em->persist($CompteHdv[0]);
	$em->flush();
/*Modification récente*/
    }
	





	$em->remove($CompteHdv[0]);
	

	$this->get('session')->setFlash(
	    'notice',
	    'Compte Hdv : '.$CompteHdv[0]->GetUsername().' supprimé !! '
	);

	$em->flush();

	return $this->redirect($this->generateUrl('D3hdv_hdv_admin_voir_comptes'));
	
   }

   public function VoirVentesEnCoursHdvAction($page)
  {
	$em = $this->container->get('doctrine')->getEntityManager();

	$qb = $em->createQueryBuilder();
	$qb->select('d')
	->from('D3hdvHdvBundle:HdvVente', 'd') // revoir requete probleme on selectionne tout les ventes :s
	->where("d.dateFin is null")
	->orderBy("d.dateDebut", 'ASC')
	;

	$query = $qb->getQuery();               
	$HdvVentes = $query->getResult();
	$total_hdvventes    = count($HdvVentes);
	$hdvventes_per_page = $this->container->getParameter('max_on_listepage');
	$last_page         = ceil($total_hdvventes / $hdvventes_per_page);
	$previous_page     = $page > 1 ? $page - 1 : 1;
	$next_page         = $page < $last_page ? $page + 1 : $last_page;
	

	$qb = $em->createQueryBuilder();
	$qb->select('d')
	->from('D3hdvHdvBundle:HdvVente', 'd') // revoir requete probleme on selectionne tout les ventes :s
	->where("d.dateFin is null")
	->orderBy("d.dateDebut", 'ASC')
	;
	$query = $qb->setFirstResult(($page * $hdvventes_per_page) - $hdvventes_per_page)->setMaxResults($this->container->getParameter('max_on_listepage'))->getQuery();                
	$HdvVentes = $query->getResult();

	if(!empty($HdvVentes)) // Objet dans la table HdvVente donc déja vendu
	{	

		return $this->render('D3hdvHdvBundle:Admin:voir_ventes_hdv.html.twig', array( // faire vue + route
		    'HdvVentes'	=> $HdvVentes,
		    'last_page' => $last_page,
		    'previous_page' => $previous_page,
		    'current_page' => $page,
		    'next_page' => $next_page,
		    'total_hdventes' => $total_hdvventes,
		));
	}

		return $this->render('D3hdvHdvBundle:Admin:voir_ventes_hdv.html.twig', array( // faire vue
		    'HdvVentes'	=> $HdvVentes,
		    'last_page' => $last_page,
		    'previous_page' => $previous_page,
		    'current_page' => $page,
		    'next_page' => $next_page,
		    'total_hdventes' => $total_hdvventes,
		));
	
   }

public function VoirHistoriqueVentesHdvAction($page)
  {
	$em = $this->container->get('doctrine')->getEntityManager();

	$qb = $em->createQueryBuilder();
	$qb->select('d')
	->from('D3hdvHdvBundle:HdvVente', 'd') // revoir requete probleme on selectionne tout les ventes :s
	->where("d.dateFin is  not null")
	->orderBy("d.dateDebut", 'ASC')
	;

	$query = $qb->getQuery();               
	$HdvVentes = $query->getResult();
	$total_hdvventes    = count($HdvVentes);
	$hdvventes_per_page = $this->container->getParameter('max_on_listepage');
	$last_page         = ceil($total_hdvventes / $hdvventes_per_page);
	$previous_page     = $page > 1 ? $page - 1 : 1;
	$next_page         = $page < $last_page ? $page + 1 : $last_page;
	

	$qb = $em->createQueryBuilder();
	$qb->select('d')
	->from('D3hdvHdvBundle:HdvVente', 'd') // revoir requete probleme on selectionne tout les ventes :s
	->where("d.dateFin is not null")
	->orderBy("d.dateDebut", 'ASC')
	;
	$query = $qb->setFirstResult(($page * $hdvventes_per_page) - $hdvventes_per_page)->setMaxResults($this->container->getParameter('max_on_listepage'))->getQuery();                
	$HdvVentes = $query->getResult();

	if(!empty($HdvVentes)) // Objet dans la table HdvVente donc déja vendu
	{	

		return $this->render('D3hdvHdvBundle:Admin:voir_historique_ventes_hdv.html.twig', array( // faire vue + route
		    'HdvVentes'	=> $HdvVentes,
		    'last_page' => $last_page,
		    'previous_page' => $previous_page,
		    'current_page' => $page,
		    'next_page' => $next_page,
		    'total_hdventes' => $total_hdvventes,
		));
	}

		return $this->render('D3hdvHdvBundle:Admin:voir_historique_ventes_hdv.html.twig', array( // faire vue
		    'HdvVentes'	=> $HdvVentes,
		    'last_page' => $last_page,
		    'previous_page' => $previous_page,
		    'current_page' => $page,
		    'next_page' => $next_page,
		    'total_hdventes' => $total_hdvventes,
		));
	
   }


   public function SommeVenteCumuleHdvAction()
   {
	$em = $this->container->get('doctrine')->getEntityManager();
	$HdvAdminCompte = $this->container->get('security.context')->getToken()->getUser();
	
	// Nombre de ventes réalisées :D

	$qb = $em->createQueryBuilder();
	$qb->select('d')
	->from('D3hdvHdvBundle:HdvVente', 'd') // revoir requete probleme on selectionne tout les ventes :s
	->where("d.dateFin is not null")
	;
	
	$query = $qb->getQuery();               
	$HdvReqNombreDeVente = $query->getResult();
	$totalHdvVentes    = count($HdvReqNombreDeVente);	
	
	// Pieces d'or cumulés des ventes
              
	$HdvReqOrCumuleDesVentes =$HdvReqNombreDeVente ;
	$totalSommeHdvVente= 0;
	if( !empty($HdvReqOrCumuleDesVentes))
	{
		foreach($HdvReqOrCumuleDesVentes as $j => $HdvVente)  
		{
			$totalSommeHdvVente+=$HdvVente->GetPrix();
		}
	}
	$totalSommeHdvVenteEuros=($totalSommeHdvVente*0.20)/1000000;

	// Pieces d'or cumulées des ventes par Hdv
	$totalSommeHdvAdmin=$HdvAdminCompte->GetDiablo3Compte()->GetCoffre()->GetPieceOr();
	$totalSommeHdvAdminEuros=($totalSommeHdvAdmin*0.20)/1000000;

	/*echo "Totale de vente = ".$totalHdvVentes."</br>";
	echo "Somme totale des ventes = ".$totalSommeHdvVente." piece d'or => ".$totalSommeHdvVenteEuros." euros</br>";
	echo "Somme prelevée sur les ventes par Hdv = ".$totalSommeHdvAdmin." piece d'or => ".$totalSommeHdvAdminEuros." euros</br>";
	return new Response("rte");*/
	return $this->render('D3hdvHdvBundle:Admin:voir_chiffre_ventes_hdv.html.twig', array( // faire vue
		    'totalHdvVentes'	=> $totalHdvVentes,
		    'totalSommeHdvVente' => $totalSommeHdvVente,
		    'totalSommeHdvVenteEuros' => $totalSommeHdvVenteEuros,
		    'totalSommeHdvAdmin' => $totalSommeHdvAdmin,
		    'totalSommeHdvAdminEuros' => $totalSommeHdvAdminEuros,
		));
	
   }
  
   public function AnnulerVentesEnCoursAction($idvente)
   { 
	$em = $this->container->get('doctrine')->getEntityManager();
	$HdvVente = $em->getRepository('D3hdvHdvBundle:HdvVente')->findById($idvente); // on recupere l'entité vente à partir de son id
	$HdvIdCompteVendeur=$HdvVente[0]->GetIdCompteVendeur(); // on recupere id Compte hdv vendeur
	$HdvCompteVendeur = $em->getRepository('D3hdvHdvBundle:HdvCompte')->findById($HdvIdCompteVendeur); // on recupere l'entité compte vendeur à partir de son id

	$HdvCompteDiablo3Coffre=$HdvCompteVendeur[0]->getDiablo3Compte()->getCoffre();
	$HdvCompteObjetsEnVente=$HdvCompteVendeur[0]->getObjetsEnVente();
	$HdvVenteObjetVendu="";
	
	$HdvVenteObjetVendu=$HdvVente[0]->GetD3Objet();
	$HdvVenteObjetVenduDateFin=$HdvVente[0]->getDateFin();

	if(is_null($HdvVenteObjetVenduDateFin))
	{
		$qb = $em->createQueryBuilder();
		$qb->select('v')
		->from('D3hdvDiablo3Bundle:D3CoffreD3Objet', 'v')
		->where("v.D3Coffre = ?1 and v.D3Objet= ?2")
		->setParameter(1,$HdvCompteDiablo3Coffre)
		->setParameter(2,$HdvVenteObjetVendu);

		$query = $qb->getQuery();               
		$D3ObjetD3Coffre = $query->getResult();	
		if(!empty($D3ObjetD3Coffre)) // Objet dans la table HdvVente donc déja vendu
		{
			foreach($D3ObjetD3Coffre as $o => $D3Objet)  
			{
				$D3Objet->SetEnVente(false);
				$em->persist($D3Objet);
				$em->flush();
			}
		}
		$HdvCompteVendeur[0]->removeObjetsEnVente($HdvVente[0]);
	
		$em->persist($HdvCompteVendeur[0]);
		$em->flush();

		$em->remove($HdvVente[0]);
		$em->flush();
	}
					
		
        $this->get('session')->setFlash(
            'notice',
            'Vente de l objet '.$HdvVenteObjetVendu->GetObjetModele()->GetNom().' annulée'
        );

        return $this->redirect($this->generateUrl('D3hdv_hdv_admin_voir_ventes'));
	
		
  }

}
